package com.ruoyi.system.service.impl;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.config.KeChuangConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.AwardsRule;
import com.ruoyi.system.mapper.AwardsRuleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysRoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.AwardsMapper;
import com.ruoyi.system.domain.Awards;
import com.ruoyi.system.service.IAwardsService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 奖项管理Service业务层处理
 *
 * @author xrx
 * @date 2024-05-09
 */
@Service
public class AwardsServiceImpl implements IAwardsService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);
    @Autowired
    private AwardsMapper awardsMapper;

    @Autowired
    private AwardsRuleMapper awardsRuleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;
    @Resource
    private KeChuangConfig keChuangConfig;
    @Resource
    private ISysRoleService sysRoleService;


    /**
     * 查询奖项管理
     *
     * @param id 奖项管理主键
     * @return 奖项管理
     */
    @Override
    public Awards selectAwardsById(Long id) {
        return awardsMapper.selectAwardsById(id);
    }

    /**
     * 查询奖项管理列表
     *
     * @param awards 奖项管理
     * @return 奖项管理
     */
    @Override
    public List<Awards> selectAwardsList(Awards awards) {
        return awardsMapper.selectAwardsList(awards);
    }

    /**
     * 新增奖项管理
     *
     * @param awards 奖项管理
     * @return 结果
     */
    @Override
    public int insertAwards(Awards awards) {
        System.out.println("awards = " + awards);
        //0新建状态 1 待审核 2 通过 3 不通过
        awards.setState(0);

        //设置审核员为两个管理员(通过角色管理配置的奖项管理员，必须配置为2个人,为了跟老系统对接)
        List<SysUser> sysUsers = sysRoleService.selectUserListByRoleId(keChuangConfig.getAwardsManageRoleId());
        if (sysUsers.size() != 2) {
            throw new RuntimeException("奖项管理员未配置为2人，请联系管理员");
        }
        awards.setChecker1(sysUsers.get(0).getUserId());
        awards.setChecker2(sysUsers.get(1).getUserId());
        awards.setCreateTime(DateUtils.getNowDate());
        Long userId = awards.getUserId();
        SysUser sysUser = sysUserMapper.selectUserById(userId);
        awards.setDeptId(sysUser.getDeptId());
        Long awardsId = awards.getAwardsId();
        AwardsRule awardsRule = awardsRuleMapper.selectAwardsRuleById(awardsId);
        awards.setName(awardsRule.getScene());
        int isFirstPerson = awards.getIsFirstPerson();
        //1就是第一负责人；0就是第二负责人
        if (isFirstPerson == 1) {
            awards.setPoints(awardsRule.getFirstPoints());
        } else {
            awards.setPoints(awardsRule.getSecondPoints());
        }

        return awardsMapper.insertAwards(awards);
    }


    //月度积分和年度积分
    private void updateMonthlyLimits(Long userId) {
        LocalDateTime now = LocalDateTime.now();
        int currentMonth = now.getMonthValue();
        int currentYear = now.getYear();
        SysUser user = sysUserMapper.selectUserById(userId);
        LocalDateTime lastUpdated = user.getLastUpdated();
        // 如果当前月份和上次更新时间的月份不一致，重置本月积分
        if (lastUpdated.getMonthValue() != currentMonth) {
            user.setPointsThisMonth(0);
            user.setLastUpdated(now);
        }
        // 如果当前年份和上次更新时间的年份不一致，重置年度积分
        if (lastUpdated.getYear() != currentYear) {
            user.setPointsThisYear(0);
            user.setLastUpdated(now);
        }
    }

    private void updateYearlyLimits() {

    }

    /**
     * 修改奖项管理
     *
     * @param awards 奖项管理
     * @return 结果
     */
    @Override
    public int updateAwards(Awards awards) {
        return awardsMapper.updateAwards(awards);
    }

    /**
     * 批量删除奖项管理
     *
     * @param ids 需要删除的奖项管理主键
     * @return 结果
     */
    @Override
    public int deleteAwardsByIds(Long[] ids) {
        return awardsMapper.deleteAwardsByIds(ids);
    }

    /**
     * 删除奖项管理信息
     *
     * @param id 奖项管理主键
     * @return 结果
     */
    @Override
    public int deleteAwardsById(Long id) {
        return awardsMapper.deleteAwardsById(id);
    }

    @Override
    public List<Awards> selectAwardsListByUserId(Long userId) {
        return awardsMapper.selectAwardsListByUserId(userId);

    }

    @Override
    public AwardsRule selectAwardsRuleById(Long awardsId) {
        return awardsRuleMapper.selectAwardsRuleById(awardsId);
    }

    @Override
    public List<Awards> getUserAwardsInfo() {
        return awardsMapper.getUserAwardsInfo();
    }

    @Override
    public String importAwards(List<Awards> awardsList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(awardsList) || awardsList.size() == 0) {
            throw new ServiceException("导入奖项数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        try {
            for (Awards award : awardsList) {
                try {
                    // 验证奖项是否存在，假设 awardsMapper 提供了查询方法 selectAwardById
                    Awards existingAward = awardsMapper.selectAwardsById(award.getId());
                    if (existingAward == null) {
                        // 新奖项插入
                        award.setCreateBy(operName);
                        this.insertAwards(award);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、奖项 " + award.getName() + " 导入成功");
                    } else {
                        // 如果不允许更新，记录失败
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、奖项 " + award.getName() + " 已存在");
                    }
                } catch (Exception e) {
                    // 记录导入失败的奖项及异常
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、奖项 " + award.getName() + " 导入失败：";
                    failureMsg.append(msg + e.getMessage());
                    log.error(msg, e);
                }
            }

            // 如果有失败的记录，抛出异常
            if (failureNum > 0) {
                failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                throw new ServiceException(failureMsg.toString());
            } else {
                // 如果全部导入成功，返回成功消息
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                return successMsg.toString();
            }
        } catch (Exception e) {
            // 处理整个方法中的异常
            e.printStackTrace();
            throw new ServiceException("奖项数据导入失败，系统发生错误！");
        }
    }

}
